/**
 * 移动优惠券列表
 */
var couponWidth     = 211,	//每张优惠券宽度
    couponAnimate   = false,//优惠券动画是否在进行中
    couponPageCnt   = 0,	//总页数
    couponPage      = 1,	//页面计数
    couponWrapWidth = 0,	//计算优惠券列表整体宽度
    couponShowCnt   = 3;	//显示数量
    couponCnt       = 0;

var coupon = {
	init : function() {
		couponCnt       = parseInt($('.details-topcon-pack li').length);
		if (couponCnt > 0) {
			$('.slide-coupon-wrap').show();
		}
		couponWrapWidth = couponCnt * couponWidth;
		$('.details-topcon-pack').width(couponWrapWidth);
		this.pageCnt();
	},
	pageCnt : function() {
		couponPageCnt = Math.ceil(couponCnt / couponShowCnt);
	},
	tpl : function(res) {
		var html = '<ul class="details-topcon-pack" style="">';
		$.each(res, function(k, v) {
			var showBtnStr = (v.LimCnt >= v.Lim || v.CouponNumber == v.GaveNumber) ? '已领完' : '领取';
            var item = (v.LimCnt >= v.Lim || v.CouponNumber == v.GaveNumber) ? 'pack-coupon-item-done' : '';
			html += '<li class="pack-coupon-item ' + item + '">';
			html += '<a href="javascript:void(0);" couponid="' + v.ID + '">';
			html += '<div class="price-wrap">';
			html += '<div class="price-num"><i>￥</i>' + v.Val + '</div>';
			html += '<span class="price-description">满' + v.Cost + '元可用</span>';
			html += '</div>';
            var limcnt = (v.LimCnt > 0) ? '已领取<span>' + v.LimCnt + '</span>张' : '';
			html += '<span class="get" sid="' + v.SID + '" couponid="' + v.ID + '" lim="' + v.Lim + '" type="' + v.Type + '"><span class="showBtnStr">'+showBtnStr+'</span><i style="overflow: hidden;">' + limcnt + '</i></span>';
			html += '</a>';
			html += '</div>';
		});
		html += '<a href="javascript:void(0);" class="prev" style="display: none;"></a>';
		html += '<a href="javascript:void(0);" class="next" style="display: none;"></a>';
		$('.slide-coupon-wrap').empty();
		$('.slide-coupon-wrap').html(html);
	}
};
/**
 * 学校自定义初始化
 */
var cksCustom = {
	loadPage:function() {
		this.buildModules();
		this.loadModules();
		this.registerModuleEvent();
		this.buildCoupon();
	},

	/**
	 * 创建优惠券
	 */
	buildCoupon : function() {
		$.ajax({
			url  : "/?mod=school&act=coupon&do=show",
			type : "get",
			data : { "sid" : cksData.sid },
			dataType : 'json',
			cache : false,
			success : function(res) {
				coupon.tpl(res);
				coupon.init();
			}
		});
	},
	
	buildModules:function() {
		var leftContainer = $(".sectionside");	//左边容器
		var rightContainer = $(".sectionMain");	//右边容器
		
		var modules = cksData.modules;
		for (var i in modules) {
			if (modules[i].position == 'left') {
				leftContainer.append('<div class="ck_module clearfix" mid="'+i+'"><p class="sh_loading"><img src="http://res.ckimg.com/sites/www/v2/images/school/sh_loading.gif" alt="载入中..."></p></div>');
			} else {
				rightContainer.append('<div class="ck_module clearfix" mid="'+i+'"><p class="sh_loading"><img src="http://res.ckimg.com/sites/www/v2/images/school/sh_loading.gif" alt="载入中..."></p></div>');
			}
		}
	},
	
	loadModules:function() {
		$(".ck_module").each(function(){
			var cobj = $(this);
			var module = cksData.modules[cobj.attr('mid')];
			$.ajax({
				url:"/?mod=school&act=custom&do=loadModule",
				type:"post",
				data:{"setting":module.setting, "mid":module.id, "sid":cksData.sid},
				success:function(con) {
					cobj.html(con);
				}
			});
		});
	},
	
	reloadModule:function(mid) {
		var cobj = $(".ck_module[mid='"+mid+"']");
		var module = cksData.modules[mid];
		$.ajax({
			url:"/?mod=school&act=custom&do=loadModule",
			type:"post",
			data:{"setting":module.setting, "tmpData":cksData.tmpData, "mid":module.id, "sid":cksData.sid},
			beforeSend:function() {
				cobj.html('<p class="sh_loading"><img src="http://res.ckimg.com/sites/www/v2/images/school/sh_loading.gif" alt="载入中..."></p>');
			},
			success:function(con) {
				cobj.html(con).find(".hd").show();
			}
		});
	},
	
	loadScript:function(scriptname){ 
		$('body').append('<script src="'+scriptname+'?tm='+Math.random()+'"></script>');
	},
		
	init:function() {
		cksData.initData(CKS);
		this.loadPage();
	},
	
	initEditMode:function() {
		//显示标题
		$(".ck_module").find(".hd").show();
		
		$(".sh_info").unbind();
		
		$(".ck_module").live("mouseover", function(){
			$(this).find(".editset").show();
		}).live("mouseout", function(){
			$(this).find(".editset").hide();
		});
		
		$(".banner_edit").hover(
			function(){
				$(this).find(".editset").show();
			},
			function(){
				$(this).find(".editset").hide();
			}
		);
		$(".ck_column").sortable({
			connectWith: '.ck_column',
			placeholder: 'ui-sortable-placeholder',
			cursor:'move',
			opacity: 1,
			handle:'header',
			distance: 10,
			revert:300,
			dropOnEmpty:true,
			start:function(event, ui){
				ui.item.css({"height":"30px","overflow":"hidden"});
			},
			out:function(event, ui) {
				var mid = ui.item.attr('mid');
				var module = cksData.modules[mid];
				if (module.layout != 'all') {
					ui.placeholder.removeClass("ui-sortable-placeholder").addClass("ui-sortable-placeholder_cancel");
				}
			},
			//当一个元素从一个sortable对象拖了出来，并进入另一个sortable对象时触发，如果该模块只允许在左列或者右列，则取消此次操作
			remove:function(event, ui){
				var mid = ui.item.attr('mid');
				var module = cksData.modules[mid];
				if (module.layout != 'all') {
					$(this).sortable('cancel');
				} else {
					if (module.position == 'left') {
						cksData.modules[mid].position = 'right';
					} else {
						cksData.modules[mid].position = 'left';
					}
					
					if (module.setting.position) {
						if (module.setting.position == 'left') {
							cksData.modules[mid].setting.position = 'right';
						} else if (module.setting.position == 'right') {
							cksData.modules[mid].setting.position = 'left';
						}
						cksCustom.reloadModule(mid);
						//$(".ck_column").sortable('destroy');
					}
				}
			},
			stop:function(event, ui){
				//拖动之后更新操作
				cksCustom.updateModuleIndex();
			}
		}).disableSelection();
	},
	
	updateModuleIndex:function() {
		var leftMods = new Array(),
			rightMods = new Array();		
		
		$(".sectionside > .ck_module").each(function(){
			leftMods.push($(this).attr('mid'));
		});
		
		$(".sectionMain > .ck_module").each(function(){
			rightMods.push($(this).attr('mid'));
		});
		cksData.moduleIndex = leftMods.join(",")+"|"+rightMods.join(",");
	},
	
	registerModuleEvent:function() {
		//编辑Banner
		$(".banner_edit").find("a.bj").unbind('click').click(function(){
			$.ajax({
				url:"/?mod=school&act=custom&do=editBanner",
				type:"post",
				data:{"sid":cksData.sid, "tmpData":cksData.tmpData},
				success:function(con) {
					var ajaxBox = $.ckBoxy({
						content: con,
						title : "编辑学校横幅",
						width : 565,
						height : 462,
						callback : function() {
							$("#fe_dialogBox").find("a.submit").unbind().bind('click', function(){
								if ($("#banner_item_list").find(".item_select").length > 0) {
									cksData.tmpData.bannerId = $("#banner_item_list").find(".item_select").eq(0).attr('bid');
								} else {
									cksData.tmpData.bannerId = '10000'; //自定义上传
								}
								cksData.tmpData.bannerUrl = $("#banner_url").attr('src');
								$("#school_banner").attr('src', $("#banner_url").attr('src'));
								ajaxBox.cancel();
							});
							
							//关闭窗口
							$("#fe_dialogBox").find("a.cancel").unbind().bind('click', function(){
								ajaxBox.cancel();
							});
						}
					});
				}
			});
		});
		
		//添加模块
		$(".ck_module").find("a.tj").unbind('click').live('click', function(){
			var pobj = $(this).parents(".ck_module");
			var mid = cksData.modules.length; //新添加模块的Key
			var position = $(this).parents(".ck_column").attr('position');
			
			var modules = new Array();
			if (cksData.moduleIndex) {
				var mArray = cksData.moduleIndex.split("|");
				var leftArray = mArray[0].split(",");
				var rightArray = mArray[1].split(",");
				for (var i in leftArray) {
					if (typeof cksData.modules[leftArray[i]] != 'undefined') {
						modules.push(cksData.modules[leftArray[i]].id);
					}
				}
				
				for (var j in rightArray) {
					if (typeof cksData.modules[rightArray[j]] != 'undefined') {
						modules.push(cksData.modules[rightArray[j]].id);
					}
				}
			}
			
			$.ajax({
				url:"/?mod=school&act=custom&do=addModule",
				type:"post",
				data:{"position":position, "modules":modules.join(","), "sid":cksData.sid},
				success:function(con) {
					var ajaxBox = $.ckBoxy({
						content: con,
						title : "添加模块",
						width : 552,
						height : 521,
						callback : function() {
							$("#fe_dialogBox").find("a.addModule").unbind().bind('click', function(){
								var cobj = $(this);
								var moduleId = cobj.attr('mid');
								
								//添加左右属性
								cksData.modules[mid] = cksData.defaultModules[moduleId];
								cksData.modules[mid].position = position;
								if (typeof cksData.modules[mid].setting.position != 'undefined') {
									cksData.modules[mid].setting.position = position;
								}
								
								//在当前模块后面加入新模块
								pobj.after('<div class="ck_module" mid="'+mid+'"><p class="sh_loading"><img src="http://res.ckimg.com/sites/www/v2/images/school/sh_loading.gif" alt="载入中..."></p></div>');
								cksCustom.reloadModule(mid);
								cksCustom.updateModuleIndex();
								ajaxBox.cancel();
							});
						}
					});
				}
			});
		});
		
		//上移模块
		$(".ck_module").find("a.down").unbind("click").live("click", function(){
			var cobj = $(this).parents(".ck_module");
			var pobj = cobj.prev();
			if (pobj.hasClass("ck_module")) {
				var tmp = cobj.clone();
				cobj.remove();
				pobj.before(tmp);
				cksCustom.updateModuleIndex();
			}
			return false;
		});
		
		//下移模块
		$(".ck_module").find("a.up").unbind("click").live("click", function(){
			var cobj = $(this).parents(".ck_module");
			var pobj = cobj.next();
			if (pobj.hasClass("ck_module")) {
				var tmp = cobj.clone();
				cobj.remove();
				pobj.after(tmp);
				cksCustom.updateModuleIndex();
			}
			return false;
		});
		
		//编辑模块
		$(".ck_module").find("a.bj").unbind('click').live('click', function(){
			var pobj = $(this).parents(".ck_module");
			var mid = pobj.attr('mid');
			var module = cksData.modules[mid];
			var tipsBox = null;
			$.ajax({
				url:"/?mod=school&act=custom&do=editModule",
				type:"post",
				data:{"setting":module.setting, "tmpData":cksData.tmpData, "mid":module.id, "sid":cksData.sid},
				beforeSend:function() {
					tipsBox = $.ckTipsBoxy({
						//message : "正在保存数据...",
						mask : true,
						type : "loading",
						width:"300"
					});
				},
				success:function(con) {
					tipsBox.cancel();
					var ajaxBox = $.ckBoxy({
						content: con,
						title : module.edittitle,
						width : module.editwidth,
						height : module.editheight,
						callback : function(){
							//提交数据
						
							$("#fe_dialogBox").find("a.submit").unbind().bind('click', function(){
								switch (module.id) {
									case '1':
										var notice = $("#notice").val();
										var len = $.trim(notice).replace(/[^\x00-\xff]/g, '**').length;
										if (len > 400) {
											alert("学校公告最多只能输入400个字符");
											return false;
										}
										
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										//保存临时数据
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										cksData.tmpData.notice = notice;
										cksData.tmpData.noticeEdit = "true";
										cksCustom.reloadModule(mid);
										
										/*
										if (display == "false") {
											pobj.find("h3.title").append('<span class="title_tips">(发布后生效)</span>');
										}
										*/
										break;
									case '2':
										cksData.tmpData.bigLogo = $("#big_logo").attr('src');
										cksData.tmpData.middleLogo = $("#middle_logo").attr('src');
										cksData.tmpData.smallLogo = $("#small_logo").attr('src');
										cksCustom.reloadModule(mid);
										break;
									case '3':
										cksData.modules[mid].setting.limit = $("#listNum").val();
										cksCustom.reloadModule(mid);
										break;
									case '4':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										cksData.modules[mid].setting.limit = $("#listNum").val();
										
										//老师排序列表
										var sortList = new Array();
										$.each($(".t_con"), function(){
											sortList.push($(this).attr('uid'));
										});
										cksData.modules[mid].setting.sortlist = sortList.join(",");
										
										cksCustom.reloadModule(mid);
										break;
									case '5':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										cksData.modules[mid].setting.limit = $("#listNum").val();
										
										var parentType = $("#parentType").val();
										var subType = $("#subType").val();
										var category = 0;
										if (parentType > 0) {
											if (subType == 0) {
												category = parentType;
											} else {
												category = subType;
											}
										}
										cksData.modules[mid].setting.category = category;
										cksData.modules[mid].setting.sort = $("#sortMode").val();
										
										if ($(".view1").hasClass("view1_select")) {
											cksData.modules[mid].setting.column = "1";
										} else {
											cksData.modules[mid].setting.column = "3";
										}
										
										cksCustom.reloadModule(mid);
										break;
									case '6':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										
										//分类列表 pid|pname:sid|sname,sid|sname||pid|pname:sid,sname
										var typeList = new Array();
										$("input.parent_type").each(function(){
											var pid = $(this).attr('pid');
											var pval = $(this).val();
											if (!pval) {
												return true; //return true相当于for循环里面的continue
											}
											
											var subType = new Array();
											$("input.sub_type_"+pid).each(function(){
												var cobj = $(this);
												if (!cobj.val()) {
													return true;
												}
												subType.push(cobj.attr('typeid')+'|'+cobj.val());
											});
											
											typeList.push(pid+'|'+pval+':'+subType.join(','));
										});
										
										if (typeList.length <= 0) {
											sortlist = '';
										} else {
											sortlist = typeList.join("||");
										}
										
										cksData.modules[mid].setting.sortlist = sortlist;
										cksData.tmpData.typeList = sortlist;
										cksData.tmpData.typeListEdit = "true";
										
										cksCustom.reloadModule(mid);
										break;
									case '7':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										
										if ($(".view1").hasClass("view1_select")) {
											cksData.modules[mid].setting.column = "1";
										} else {
											cksData.modules[mid].setting.column = "3";
										}
										
										//推荐课程列表
										var courseList = new Array();
										$("#recommendList").find("dl").each(function(){
											courseList.push($(this).attr('courseid'));
										});
										cksData.modules[mid].setting.data = courseList.join(',');
										
										cksCustom.reloadModule(mid);
										break;
									case '8':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										
										var images = new Array();
										$(".item_focus").each(function(){
											var cobj = $(this);
											var img = $.trim(cobj.find(".focus_img").val());
											var url = $.trim(cobj.find(".focus_url").val());
											if (!img) {
												return true;
											} 
											
											if (!url) {
												url = '#';
											}
											images.push(img+"|"+url);
										});
										
										var data = "";
										if (images.length > 0) {
											data = images.join("||");
										}
										
										cksData.modules[mid].setting.data = data;
										cksCustom.reloadModule(mid);
										break;
									case '9':
										var links = new Array();
										$(".link_item").each(function(){
											var cobj = $(this);
											var link_name = $.trim(cobj.find(".link_name").val());
											var link_url = $.trim(cobj.find(".link_url").val());
											if (!link_name || !link_url) {
												return true;
											} else {
												var exp = 'chuanke\.com';
												if(!link_url.match(exp)) {
													alert('友情链接-只支持传课平台学校链接！');
													return true;
												}
											}
											links.push(link_name+"|"+link_url);
										});
										
										var data = "";
										if (links.length > 0) {
											data = links.join("||");
										}
										cksData.modules[mid].setting.data = data;
										
										cksCustom.reloadModule(mid);
										break;
									case '10':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										cksCustom.reloadModule(mid);
										break;
									case '11':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										var desc_len = $.trim($("#service_desc").val()).replace(/[^\x00-\xff]/g, '**').length;
										if (desc_len > 400) {
											alert("客服说明不能超过400个字符");
											return false;
										}
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										cksData.modules[mid].setting.desc = $("#service_desc").val();
										
										services = new Array();
										$(".item_service").each(function(){
											var cobj = $(this);
											var service_name = cobj.find(".service_name").val();
											var service_type = cobj.find(".service_type").val();
											var service_number = cobj.find(".service_number").val();
											if (!service_name || !service_number) {
												return true;
											}
											services.push(service_name+":"+service_type+":"+service_number);
										});
										
										var data = '';
										if (services.length > 0) {
											data = services.join("|");
										}
										cksData.modules[mid].setting.services = data;
										
										cksCustom.reloadModule(mid);
										break;
									case '12':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										var desc_len = $.trim($("#contact_desc").val()).replace(/[^\x00-\xff]/g, '**').length;
										if (desc_len > 400) {
											alert("描述不能超过400个字符");
											return false;
										}
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										cksData.modules[mid].setting.desc = $("#contact_desc").val();
										cksData.modules[mid].setting.weibo = $("#weibo_account").val();
										cksData.modules[mid].setting.qrcode = $("#qrcode_img").attr('src');
										cksCustom.reloadModule(mid);
										break;
									case '13':
										var display = $(":radio[name='display'][checked=true]").val();
										var title = $("#title").val();
										if (display == "true" && !title) {
											alert("请填写标题");
											return false;
										}
										var title_len = $.trim(title).replace(/[^\x00-\xff]/g, '**').length;
										if (title_len > 16) {
											alert("标题不能超过16个字符");
											return false;
										}
										
										var brief = $.trim($("#brief").val()).replace(/[^\x00-\xff]/g, '**').length;
										if (brief > 20000) {
											alert("描述不能超过20000个字符");
											return false;
										} 
										
										cksData.modules[mid].setting.title = title;
										cksData.modules[mid].setting.display = display;
										cksData.modules[mid].setting.data = $("#brief").val();
										cksCustom.reloadModule(mid);
										break;
									default:
										alert('非法操作');
										break;
								}
								ajaxBox.cancel();
							});
							
							//关闭窗口
							$("#fe_dialogBox").find("a.cancel").unbind().bind('click', function(){
								ajaxBox.cancel();
							});
							$("#fe_dialogBox").find("a.n_btn38gr_b").unbind().bind('click', function(){
								ajaxBox.cancel();
							});
						}
					});
					if(module.id == 11){
						$('#fe_dialogBox').css('height','510');
						$('#fe_dialogBox .fe_dialog').css('height','496');						
					}
				}
			});
		});
		
		//删除模块
		$(".ck_module").find("a.sc").unbind('click').live('click', function(){
			var pobj = $(this).parents(".ck_module");
			var mid = pobj.attr('mid');
			pobj.remove();
			cksCustom.updateModuleIndex();
		});
	},
	
	toJSONString:function(object) {
        var type = typeof object;
        switch (type) {
            case 'undefined' :
            case 'unknown' :
                return;
                break;
            case 'function' :
            case 'boolean' :
            case 'regexp' :
                return object.toString();
                break;
            case 'number' :
                return isFinite(object) ? object.toString() : 'null';
                break;
            case 'string' :
                return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function() {
                            var a = arguments[0];
                            return (a == '\n') ? '\\n' : (a == '\r') ? '\\r' : (a == '\t') ? '\\t' : ""
                        }) + '"';
                break;
            case 'object' :
                if (object === null)
                    return 'null';
                var results = [];
                for (var property in object) {
                    var value = cksCustom.toJSONString(object[property]);
                    if (value !== undefined)
                        results.push(cksCustom.toJSONString(property) + ':' + value);
                }
                return '{' + results.join(',') + '}';
                break;
            case 'array' :
                var results = [];
                for (var i = 0; i < object.length; i++) {
                    var value =  cksCustom.toJSONString(object[i]);
                    if (value !== undefined)
                        results.push(value);
                }
                return '[' + results.join(',') + ']';
                break;
        }
    }
};

$(function() {

	cksCustom.init();
	
	//编辑学校
	$("#edit_school").click(function(){
		//判断浏览器如果是ie6,则不允许编辑
		if ($.browser.msie && parseInt($.browser.version, 10) <= 6) {
			$.ckAlert({message:"你的浏览器版本太低，请使用Chrome、Firefox、IE7及以上版本的IE浏览器！", width:550, height:200});
			return false;
		}
		
		//禁止点击出去
		$(".menu").find("a").unbind('click').bind('click', function(){return false;});
		
		//修改编辑模式
		cksData.editMode = true;
		$(".editbar").show();
		
		//隐藏搜索栏
		$(".c_xxsy").hide();
		
		//初始化编辑模式
		cksCustom.initEditMode();
		
		$(this).hide();
		
		$(document).keydown(function(event){
			var e = event || window.event;
            var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            if (keyCode == 116) {
            	$.ckConfirm({
        			message:"刷新后所有的修改都不会生效，确定要刷新吗？",
        			width:420,
        			ok:function() {
        				window.location.reload();
        			}
        		});
            	e.keyCode ? e.keyCode = 0 : e.which = 0;
            	return false;
            }
		});
	});
	
	//取消保存
	$("#cancel_edit").click(function(){
		$.ckConfirm({
			message:"返回后所有的修改都不会生效，确定要“返回”吗？",
			width:420,
			ok:function() {
				window.location.reload();
			}
		});
		return false;
	});
	
	//选择模板
	$("#select_template").toggle(
		function(){
			$(this).addClass('select');
			$(".editbar_bd").slideDown();
		},
		function(){
			$(this).removeClass('select');
			$(".editbar_bd").slideUp();
		}
	);
	
	$("a.changeStyle").click(function(){
		var tid = $(this).attr('tid');
		
		var valid = false;
		for (var i in CKS.AllowableTemplates) {
			if (tid == CKS.AllowableTemplates[i]) {
				valid = true;
			}
		}
		
		if (valid === false) {
			$.ckAlert({message:"你没有权限使用该模板"});
			return false;
		}
		
		$("a.changeStyle").text('使用');
		$(this).text('已使用');
		
		var css_path = "http://res.ckimg.com/sites/www/v2/images/school/skin"+tid+"/style.css";
		$(".tIcon").removeClass('select');
		$(this).parents(".dlPic").find(".tIcon").addClass('select');
		cksData.tmpData.template = tid;
		$("#template_style").attr('href', css_path);
	});
	
	//保存并发布
	$("#save_edit").click(function(){
		//组装modules
		var modules = new Array();
		var moduleIndex = cksData.moduleIndex;
		var columns = moduleIndex.split("|");
		var leftModules = columns[0].split(",");
		var rightModules = columns[1].split(",");
		
		for (var i in leftModules) {
			var module = cksData.modules[leftModules[i]];
			modules.push(module);
		}
		
		for (var j in rightModules) {
			var module = cksData.modules[rightModules[j]];
			modules.push(module);
		}
		
		if ($.browser.msie && ($.browser.version == '7.0' || $.browser.version == '8.0')) {
			var module_json = cksCustom.toJSONString(modules);
		} else {
			var module_json = JSON.stringify(modules);
		}
		
		var tipsBox = null;
		$.ajax({
			url:"/?mod=school&act=custom&do=save",
			type:"post",
			data:{"modules":module_json, "tmpData":cksData.tmpData, "sid":cksData.sid},
			dataType:"json",
			beforeSend:function() {
				tipsBox = $.ckTipsBoxy({
					message : "正在保存数据...",
					mask : true,
					type : "loading",
					width:"300"
				});
			},
			success:function(ret) {
				if (ret.code == 0) {
					cksData.quit = true;
					window.location.reload();
				} else {
					tipsBox.cancel();
					$.ckAlert({message:ret.data});
				}
			}
		});
	});

	/**
	 * 优惠券列表动画
	 */
	$('.slide-coupon-wrap').hover(
		function() {
			if (couponCnt > couponShowCnt) {
				$('.slide-coupon-wrap .prev').show();
				$('.slide-coupon-wrap .next').show();
			}
		},
		function() {
			$('.slide-coupon-wrap .prev').hide();
			$('.slide-coupon-wrap .next').hide();
		}
	);
	$('.slide-coupon-wrap .prev').live('click', function() {
		var details_topcon_pack = $('.details-topcon-pack');
		if (details_topcon_pack.is(":animated")) {
			return;
		}
		var left = parseInt(details_topcon_pack.css('margin-left'));
		if (left != 0) {
			left += (couponWidth * couponShowCnt);
			details_topcon_pack.stop(true).animate({'margin-left' : left}, "slow");
			couponPage -= 1;
		}
	});
	$('.slide-coupon-wrap .next').live('click', function() {
		var details_topcon_pack = $('.details-topcon-pack');
		if (details_topcon_pack.is(":animated")) {
			return;
		}
		var left = parseInt(details_topcon_pack.css('margin-left'));
		if (left <= 0 && couponPageCnt != couponPage) {
			left -= (couponWidth * couponShowCnt);
			details_topcon_pack.stop(true).animate({'margin-left' : left}, "slow");
			couponPage += 1;
		}
	});
    $('.pack-coupon-item .get').live('click', function() {
        if ($(this).parent().parent().hasClass('pack-coupon-item-done')) {
            return;
        }
        if (KK.checkLogin() === false) {
            $.ckLoginBoxy();
        } else {
            if ($(this).attr("disabled") == true) {
                return false;
            }
            var CouponID   = $(this).attr('couponid'),
                CouponType = $(this).attr('type'),
                CouponLim  = $(this).attr('lim'),
                SID        = $(this).attr('sid'),
                OBJ        = $(this),
                url        = location.href;
                PostData   = [
                    "CouponID="   + CouponID,
                    "CouponType=" + CouponType,
                    "CouponLim="  + CouponLim,
                    "SID="        + SID
                ].join("&");

            $.ajax({
                url        : "/?mod=student&act=promotion&do=getCoupon",
                type       : "post",
                dataType   : "json",
                data       : PostData,
                beforeSend : function() {
                    $(this).attr("disabled", true);
                },
                success    : function(ret) {
                    $(this).removeAttr("disabled");
                    var userLim = 1;
                    if (ret.code == 0) {
                        if (OBJ.find('i').html().length > 0) {
                            userLim = parseInt(OBJ.find('i span').html()) + 1;
                            OBJ.find('i span').text(userLim);
                            //OBJ.find('i span').animate({top : '50px'}, "slow");
                        } else {
                            var popFeedbackBox = $.ckAjaxBoxy({
                                url      : "/?mod=seller&act=proshow&do=giveTips&type=getsuccess&CouponType=" + CouponType + "&SID=" + SID + "&CouponID=" + CouponID,
                                title    : "提示",
                                width    : 352,
                                height   : 252,
                                callback : function() {
                                    $("a.c_btn30gr_").click(function() {
                                        popFeedbackBox.cancel();
                                    });
                                }
                            });
                            OBJ.find('i').html("已领取<span>1</span>张");
                        }
						if (userLim >= CouponLim) {
							OBJ.parent().parent().addClass('pack-coupon-item-done');
							OBJ.find('.showBtnStr').text('已领完');
						}
                    } else {
                        var tp = '';
                        switch (ret.code) {
                            case  -1:
                                tp = 'getlimit';
								OBJ.parent().parent().addClass('pack-coupon-item-done');
								OBJ.find('.showBtnStr').text('已领完');
                                break;
                            case  -2:
                                tp = 'failgetself';
                                break;
                            case  -3:
                                tp = 'nocoupon';
                                break;
                            case  -4:
                                tp = 'expired';
                                break;
                            case  -5:
                                tp = 'zuofei';
                                break;
                            case  -6:
                                tp = 'nohave';
								OBJ.parent().parent().addClass('pack-coupon-item-done');
								OBJ.find('.showBtnStr').text('已领完');
                                break;
                        }
                        var popFeedbackBox = $.ckAjaxBoxy({
                            url      : "/?mod=seller&act=proshow&do=giveTips&type=" + tp + "&CouponType=" + CouponType + "&CouponLim=" + CouponLim + "&SID=" + SID + "&CouponID=" + CouponID,
                            title    : "提示",
                            width    : 352,
                            height   : 252,
                            callback : function() {
                                $("a.c_btn30gr_").click(function() {
                                    popFeedbackBox.cancel();
                                });
                            }
                        });
                    }
                }
            });
        }
    });
});